package com.chandon.juc.thread_communication;

import java.util.concurrent.Exchanger;

/**
 * 使用Exchanger交换2个线程中的值
 * Exchanger只能用于2个线程，2个线程都执行了exchange后线程才继续执行否则阻塞。
 *
 * @author Dong
 */

public class TestExchanger {

	static Exchanger<String> exchanger = new Exchanger<>();

	public static void main(String[] args) {


		Thread t1 = new Thread(() -> {
			try {
				String name = "1";
				name = exchanger.exchange(name);
				System.out.println(Thread.currentThread().getName() + ":" + name);

			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}


		}, "T1");


		Thread t2 = new Thread(() -> {
			try {
				String name = "2";
				name = exchanger.exchange(name);
				System.out.println(Thread.currentThread().getName() + ":" + name);

			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}

		}, "T2");


		t1.start();
		// t2.start();
	}

}
